package org.example.pet.aspect;

import org.example.pet.annotation.RequiresRole;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.example.pet.common.expection.PermissionException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class RoleAspect {

    // 切入点：拦截带有@RequiresRole注解的方法
    @Pointcut("@annotation(org.example.pet.annotation.RequiresRole) && @annotation(requiresRole)")
    public void rolePointcut(RequiresRole requiresRole) {}

    // 前置通知：校验角色
    @Before("rolePointcut(requiresRole)")
    public void checkRole(RequiresRole requiresRole) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String currentRole = (String) request.getAttribute("currentRole");

        if (!requiresRole.value().equals(currentRole)) {
            throw new PermissionException("权限不足：仅" + requiresRole.value() + "可访问");
        }
    }
}